# 公共的函数以及类方法
# 重写用户登录验证的方法
import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    # 在返回的数据中添加用户id以及用户名
    data = {
        'token': token,
        'user_id': user.id,
        'username': user.username,
    }
    return data


# 因为判断登录是用户名还是手机号需要多次用到,直接封装成函数调用
def get_user_login(username):
    # 判断获取到的数据是手机号还是用户名
    try:
        if re.match(r'^1[3-9]\d{9}$', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    # 出现异常返回空值
    except User.DoesNotExist:
        return None
    else:
        return user


# 定义一个类视图,用户可以通过手机号登录
class UserMobileLogin(ModelBackend):
    # 定义用户名手机号验证登录
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 调用函数判断获取的用户登录的数据
        user = get_user_login(username)
        if user is not None and user.check_password(password):
            return user


from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData
from django.conf import settings


def generate_save_user_token_url(user):
    """使用Itsdangrous保存openID，生成access_token"""
    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, 300)
    # serializer.dumps(数据), 返回bytes类型
    data = {"user_id": user.id}
    token = serializer.dumps(data)
    token = token.decode()
    # 拼接url地址
    verify_url = settings.VERIFY_EMAIL_HTML + '?token=' + token

    return verify_url


def check_verify_email_token(token):
    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, 300)
    try:
        data = serializer.loads(token)
        return data["user_id"]
    except BadData:
        return None
